package com.cyk.service.impl;

import com.cyk.dao.LagouAuthCodeDao;
import com.cyk.dao.LagouTokenDao;
import com.cyk.dao.LagouUserDao;
import com.cyk.dubbo.api.CodeService;
import com.cyk.dubbo.api.UserService;
import com.cyk.pojo.LagouToken;
import com.cyk.pojo.LagouUser;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import java.util.UUID;


//@RestController
//@RequestMapping("/user")
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    LagouTokenDao lagouTokenDao;
    @Autowired
    LagouAuthCodeDao lagouAuthCodeDao;
    @Autowired
    LagouUserDao lagouUserDao;
    @Reference
    private CodeService codeService;

    @Override
    public boolean register(String email, String password, String code) {
        if (codeService.validate(email, code) == 0) {
            //已经注册
            LagouUser lagouUser = new LagouUser();
            lagouUser.setEmail(email);
            if (lagouUserDao.findOne(Example.of(lagouUser)).isPresent()) {
                return false;
            }
            lagouUser.setPassword(password);
            return lagouUserDao.save(lagouUser).getId() != 0;
        }
        return false;
    }

    @Override
    public String info(String token) {
        LagouToken lagouToken = new LagouToken();
        lagouToken.setToken(token);

        LagouToken lagouToken1 = lagouTokenDao.findOne(Example.of(lagouToken)).get();
        if (lagouToken1.getId() != 0) {
            return lagouToken1.getEmail();
        }
        return "";
    }

    @Override
    public boolean isRegistered(String email) {
        LagouUser lagouUser = new LagouUser();
        lagouUser.setEmail(email);
        return lagouUserDao.findOne(Example.of(lagouUser)).isPresent();
    }

    @Override
    public String login(String email, String password) {
        LagouUser lagouUser = new LagouUser();
        lagouUser.setEmail(email);
        lagouUser.setPassword(password);
        LagouUser lagouUser1 = lagouUserDao.findOne(Example.of(lagouUser)).get();
        if (lagouUser1 == null)
            return "";

        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        lagouToken.setToken(UUID.randomUUID().toString());
        lagouTokenDao.save(lagouToken);
//        if (lagouTokenDao.save(lagouToken).getId() != 0) {
//            //写入cookie
//            response.addCookie(new Cookie("token", lagouToken.getToken()));
//        }
        return lagouToken.getToken();
    }
}
